import './todoList.css'
import { useSelector, useDispatch } from 'react-redux'
import { add, changeState, deleteItem, toggleAll } from '../../store/modules/todoListStore'
import { useRef } from 'react'

function TodoList() {
    const todolist = useSelector(state => state.todoList.todolist)
    const dispatch = useDispatch()
    const inputRef = useRef()
    const allCompleted = todolist.every(item => item.completed)

    const handleKeyDown = (e) => {
        if (e.key === 'Enter') {
            dispatch(add(inputRef.current.value))
            inputRef.current.value = ''
        }
    }

    const handleChange = (item) => {
        dispatch(changeState(item.id))
    }

    const handleDelete = (item) => {
        dispatch(deleteItem(item.id))
    }

    const handletoggleAll = () => {
        dispatch(toggleAll())
    }

    return (
        <section className="todoapp">
            <header className="header">
                <h1>todos</h1>
                <input
                    className="new-todo"
                    autoFocus
                    autoComplete="off"
                    placeholder="What needs to be done?"
                    onKeyDown={handleKeyDown}
                    ref={inputRef}
                />
            </header>
            <section className="main">
                <input
                    id="toggle-all"
                    className="toggle-all"
                    type="checkbox"
                    checked={allCompleted}
                    onChange={handletoggleAll}
                />
                <label htmlFor="toggle-all"></label>
                <ul className="todo-list">
                    {todolist.map((item) => {
                        return (
                            <li key={item.id} className={item.completed ? 'completed' : ''}>
                                <div className="view">
                                    <input
                                        className="toggle"
                                        type="checkbox"
                                        checked={item.completed}
                                        onChange={() => handleChange(item)}
                                    />
                                    <label>{item.title}</label>
                                    <button className="destroy" onClick={() => handleDelete(item)}></button>
                                </div>
                            </li>
                        )
                    })}
                </ul>
            </section>
        </section>
    )
}

export default TodoList